package cs340.stormtroopers.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;

import cs340.stormtroopers.hypeerweb.Node;

public class SmallerChildlessNeighborDelegate extends NeighborDelegate
{
	public SmallerChildlessNeighborDelegate(Node original, Node delegate)
	{
		super(original, delegate);
	}

	@Override
	public void insertIntoDatabase(Connection connection) throws SQLException
	{
		PreparedStatement insertSmallChildlessNeighborStatement = connection
				.prepareStatement("INSERT INTO ChildlessNeighborsSmallerThanMe(Left,Right) VALUES (?, ?)");
		insertSmallChildlessNeighborStatement.setInt(1, originalNode.getWebIdValue());
		insertSmallChildlessNeighborStatement.setInt(2, delegate.getWebIdValue());
		insertSmallChildlessNeighborStatement.addBatch();
		connection.setAutoCommit(false);
		insertSmallChildlessNeighborStatement.executeBatch();
		connection.setAutoCommit(true);
		insertSmallChildlessNeighborStatement.close();
	}

	public static Iterator<Delegate> wrap(final Node original, final Iterable<Node> nodes)
	{
		return new Iterator<Delegate>() {
			private Iterator<Node> iterator = nodes.iterator();
			@Override
			public boolean hasNext()
			{
				return iterator.hasNext();
			}

			@Override
			public Delegate next()
			{
				return new SmallerChildlessNeighborDelegate(original, iterator.next());
			}

			@Override
			public void remove()
			{
				throw new UnsupportedOperationException();
			}
			
		};
	}
}
